//
// Created by LiuYou on 2021/8/4.
//

#include <cstdio>
#include <cstdlib>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
#include "Proto.hpp"


int main(int argc, char** argv) {
    int socketFD = socket( PF_INET, SOCK_DGRAM, 0 );
    if (socketFD < 0) {
        perror( "socket()" );
        exit( 1 );
    }

    int optVal = 1;
    int retVal = setsockopt( socketFD, SOL_SOCKET, SO_BROADCAST,
                             &optVal, sizeof( optVal ));
    if (retVal < 0) {
        perror( "setsockopt()" );
        exit( 1 );
    }

//    bind();

    using SocketBasic::Msg;
    Msg sendMsg( "Alan", htonl((rand() % 100)), htonl((rand() % 100)));
    struct sockaddr_in remoteAddress{
            .sin_family=AF_INET,
            .sin_port=htons( atoi( RCV_PORT ))
    };
    // 全网广播 ip地址为: 255.255.255.255
    inet_pton( AF_INET, "255.255.255.255", &remoteAddress.sin_addr );
    ssize_t ret = sendto( socketFD, &sendMsg, sizeof( sendMsg ), 0,
                          (sockaddr*) &remoteAddress, sizeof( remoteAddress ));
    if (ret < 0) {
        perror( "sendto()" );
        exit( 1 );
    }
    puts( "OK!" );
    close( socketFD );

    exit( 0 );
}